<template>
  <AppPage>
    <n-card rounded-10 flex-1>
      <div min-h-60 p-15 flex items-start b-1 bc-ccc rounded-8 bg="#fafafc" dark:bg-black mb-10>
        <span style="justify-content: center; align-items: center" mt-5>登陆时间</span>
        <n-date-picker
          v-model:value="logDate"
          type="daterange"
          clearable
          ml-10
          :close-on-select="true"
          @update:value="handleUpdateValue"
        />
        <n-space wrap :size="[0, 15]" ml-auto>
          <n-button ml-10 type="primary" @click="$table?.handleSearch">搜索</n-button>
        </n-space>
      </div>

      <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :extra-params="extraParams"
        :scroll-x="1200"
        :columns="columns"
        :get-data="getLoginLog"
        @on-checked="onChecked"
      >
      </CrudTable>
    </n-card>
  </AppPage>
</template>

<script setup>
import { NButton, NTag } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef, formatDate } from '@/utils'
import { useCRUD } from '@/composables'
import { getLoginLog, deleteLoginLog } from '@/api/log/loginlog.js'

/** name的值要保持跟路由里面的name值一致，KeepAlive才会生效 */
defineOptions({ name: 'LoginLog' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
/** 补充参数（可选） */
const extraParams = ref()

const logDate = ref()

const router = useRouter()
const route = useRoute()

onActivated(() => {
  console.log('onActivated')
  $table.value?.handleSearch()
})

function handleUpdateValue() {
  if (logDate.value !== null) {
    queryItems.value = {
      beginTime: formatDate(logDate.value[0]),
      endTime: formatDate(logDate.value[1]),
    }
  } else {
    queryItems.value = null
  }
}

const columns = [
  {
    title: '序号',
    key: 'key',
    width: 20,
    align: 'center',
    render: (_, index) => {
      return `${index + 1}`
    },
  },
  {
    title: '用户名',
    key: 'username',
    width: 80,
    align: 'center',
  },
  {
    title: 'IP',
    key: 'ip',
    width: 80,
    align: 'center',
  },
  {
    title: '来源',
    key: 'ipSource',
    width: 80,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '系统',
    key: 'os',
    width: 80,
    align: 'center',
  },
  {
    title: '浏览器',
    key: 'browser',
    width: 80,
    align: 'center',
  },
  {
    title: '状态',
    key: 'status',
    width: 40,
    align: 'center',
    render(row) {
      return h(
        NTag,
        {
          type: 'success',
          bordered: false,
        },
        {
          default: () => formatStatus(row['status']),
        }
      )
    },
  },
  {
    title: '描述',
    key: 'description',
    width: 80,
    align: 'center',
  },
  {
    title: '开始时间',
    key: 'createTime',
    width: 100,
    align: 'center',
    render(row) {
      return h('span', formatDateTime(row['createTime']))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 60,
    align: 'center',
    fixed: 'center',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 15px;',
            onClick: () => handleDelete(row.id),
          },
          { default: () => '删除', icon: renderIcon('material-symbols:delete-outline', { size: 14 }) }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}

function formatStatus(status) {
  return status ? '成功' : '失败'
}

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '',
  // initForm: { isTop: false, isPublished: false, isRecommend: false, isCommentEnable: false, isAppreciation: false },
  doDelete: deleteLoginLog,
  refresh: () => $table.value?.handleSearch(),
})
</script>
